//
//  HICollectionView.swift
//  Health_Infomation
//
//  Created by 林帆 on 2017/8/19.
//  Copyright © 2017年 林帆. All rights reserved.
//

import UIKit

@objc protocol HIMECollVDelegate {
    func HIMECollVbackToVC(dataArray :  Array<String>)
}

private let HIMenuEditedCellID = "HIMenuEditedCell"
private let HIMECollectionHeadVID = "HIMECollectionHeadV"
private let HIMECollectionFootVID = "HIMECollectionFootV"

class HIMenuEditCollectionView: UIView {
    
    var DataAry : Array<Any> = []
    var isEdited = false
    weak var HIMECollVDelegate : HIMECollVDelegate? = nil
    var dragEndIndexPath: IndexPath? // 拖拽时记录用的indexpath
    var dragStartIndexPath: IndexPath? // 拖拽时记录用的indexpath
    var editIndexPath: IndexPath? // 编辑时记录用的indexpath
    lazy var MainCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout())
    lazy var EditedBtn = UIButton()
    lazy var CancelBtn = UIButton()
    
    fileprivate lazy var dragingItem: HIMenuEditedCell = {
        let cell = HIMenuEditedCell(frame: CGRect(x: 0, y: 0, width: 100, height: 100  * 0.5))
        cell.ConfigCellUI()
        cell.isHidden = true
        return cell
    }()
    
    convenience init(DataArray: Array<Any>) {
        self.init()
        self.DataAry = DataArray
        ConfigCollectionUI()
        EditedConfig() // 编辑
    }
    
    func ConfigCollectionUI () {

        // FlowLayout
        let FlowLayout = UICollectionViewFlowLayout()
        FlowLayout.minimumLineSpacing = 10
        FlowLayout.minimumInteritemSpacing = 20
        FlowLayout.itemSize = CGSize.init(width: 30, height: 34)        // 子视图
        FlowLayout.sectionInset = UIEdgeInsetsMake(12, 12, 12, 12)        // 边缘距离
        
        MainCollectionView.delegate = self
        MainCollectionView.dataSource = self
        MainCollectionView.register(HIMenuEditedCell.self, forCellWithReuseIdentifier: HIMenuEditedCellID)
        MainCollectionView.register(HIMECollectionHeadV.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HIMECollectionHeadVID)
        MainCollectionView.register(HIMECollectionFootV.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: HIMECollectionFootVID)
        MainCollectionView.backgroundColor = kRGBColorFromHex(rgbValue: 0xfafafa)
        MainCollectionView.collectionViewLayout = FlowLayout
        self.addSubview(MainCollectionView)
        
        MainCollectionView.snp.makeConstraints({ (make) in
            make.bottom.left.right.equalTo(self)
            make.top.equalTo(self).offset(55)
        })
    }
    
    func EditedConfig() {
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressGesture(_:))) //添加长按手势
        MainCollectionView.addGestureRecognizer(longPress)
        MainCollectionView.addSubview(dragingItem) // 拖拽移动时显示的cell
        
        CancelBtn.setImage(UIImage(named: "关闭")  , for: .normal)
        CancelBtn.addTarget(self, action: #selector(CloseViewClick), for: .touchUpInside)
        self.addSubview(CancelBtn)
        
        CancelBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(MainCollectionView.snp.top).offset(-22)
            make.width.height.equalTo(18)
            make.right.equalTo(self).offset(-12)
        }
    }
    
    func EditedBtnClick() {  // 进入编辑状态
        isEdited = !isEdited
        MainCollectionView.reloadSections([0])
    }
    
    func CloseViewClick() {   // 关闭自己
        HIMECollVDelegate?.HIMECollVbackToVC(dataArray: DataAry[0] as! Array<String>)
        self.removeFromSuperview()
    }
    
    func CloseItemClick(){  // 删除频道
        
        if DataAry.count > 1 {
            var Array = DataAry[0] as! [String]
            Array.remove(at: (editIndexPath?.row)!)
            DataAry[0] = Array
            MainCollectionView.reloadSections([0])
        }
    }
    
    deinit {
        print("本宝宝被销毁啦")
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
}

extension HIMenuEditCollectionView { // 拖拽移动事件

    //MARK: - 长按动作
    func longPressGesture(_ tap: UILongPressGestureRecognizer) {
        
        let point = tap.location(in: MainCollectionView)
        
        switch tap.state {
        case UIGestureRecognizerState.began:
            dragBegan(point: point)
        case UIGestureRecognizerState.changed:
            drageChanged(point: point)
        case UIGestureRecognizerState.ended:
            drageEnded(point: point)
        case UIGestureRecognizerState.cancelled:
            drageEnded(point: point)
        default: break
        }
    }
    
    //MARK: - 长按开始
    private func dragBegan(point: CGPoint) {
        
        dragStartIndexPath = MainCollectionView.indexPathForItem(at: point)
        if dragStartIndexPath == nil || (dragStartIndexPath?.section)! > 0 || dragStartIndexPath?.item == 0
        {return}
        
        let item = MainCollectionView.cellForItem(at: dragStartIndexPath!) as? HIMenuEditedCell
        item?.isHidden = true
        
        MainCollectionView.bringSubview(toFront: dragingItem)
        dragingItem.isHidden = false
        dragingItem.frame = (item?.frame)!
        dragingItem.backgroundColor = UIColor.clear
        dragingItem.titleLabel.text = item!.titleLabel.text
        dragingItem.titleLabel.frame = CGRect(origin: CGPoint.zero, size: dragingItem.frame.size)
        dragingItem.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)
    }
    
    //MARK: - 长按过程
    private func drageChanged(point: CGPoint) {
        if dragStartIndexPath == nil || (dragStartIndexPath?.section)! > 0 || dragStartIndexPath?.item == 0 {return}
        dragingItem.center = point
        dragEndIndexPath = MainCollectionView.indexPathForItem(at: point)
        if dragEndIndexPath == nil || (dragEndIndexPath?.section)! > 0 || dragStartIndexPath == dragEndIndexPath || dragEndIndexPath?.item == 0 {return}
        // 更新数据
        
        var MYArray = self.DataAry[0] as! [String]
        let obj = MYArray[dragStartIndexPath!.item]
        MYArray.remove(at: dragStartIndexPath!.row)
        MYArray.insert(obj, at: dragEndIndexPath!.item)
        DataAry[0] = MYArray
        //交换位置
        MainCollectionView.moveItem(at: dragStartIndexPath!, to: dragEndIndexPath!)
        dragStartIndexPath = dragEndIndexPath
    }
    
    //MARK: - 长按结束
    private func drageEnded(point: CGPoint) {
        
        if dragStartIndexPath == nil || (dragStartIndexPath?.section)! > 0 || dragStartIndexPath?.item == 0 {return}
        let endCell = MainCollectionView.cellForItem(at: dragStartIndexPath!)
        
        UIView.animate(withDuration: 0.25, animations: {
            self.dragingItem.transform = CGAffineTransform.identity
            self.dragingItem.center = (endCell?.center)!
        }, completion: {
            (finish) -> () in
            
            endCell?.isHidden = false
            self.dragingItem.isHidden = true
            self.dragStartIndexPath = nil
        })
    }
}

extension HIMenuEditCollectionView : UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {

    //返回多少个组
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    //返回多少个cell
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (DataAry[section] as AnyObject).count
    }
    
    // 计算宽高
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let textMaxSize = CGSize(width: kScreenWitdh, height: CGFloat(MAXFLOAT))
        let resultSize : CGSize
        resultSize = fftextSize(text: (DataAry[indexPath.section] as! Array)[indexPath.row], font: UIFont.systemFont(ofSize: 15), maxSize: textMaxSize)
        if indexPath.section == 0 {
            return CGSize(width: resultSize.width + 18, height: 34)
        } else {
            return CGSize(width: resultSize.width + 38, height: 34)
        }
    }
    
    //返回自定义的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HIMenuEditedCell", for: indexPath) as! HIMenuEditedCell
        cell.ConfigCellUI()
        
        cell.CloseButton.frame = CGRect(x: cell.frame.size.width - 9, y: -7, width: 16, height: 16)
        cell.CloseButton.addTarget(self, action: #selector(CloseItemClick), for: .touchUpInside)
        
        cell.titleLabel.frame =  cell.bounds
        cell.titleLabel.textColor = kRGBColorFromHex(rgbValue: 0x333333) //推荐 回退设置
        if indexPath.section == 0 {
            cell.titleLabel.text = (DataAry[indexPath.section] as! Array)[indexPath.row]
        }else {
            let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()
            let addString : NSAttributedString = NSAttributedString(string: "＋ ", attributes: [NSForegroundColorAttributeName : UIColor.gray, NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)])
            let dataString : NSAttributedString = NSAttributedString(string: (DataAry[indexPath.section] as! Array)[indexPath.row], attributes: [NSForegroundColorAttributeName :  kRGBColorFromHex(rgbValue: 0x333333), NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)])
            attributedStrM.append(addString)
            attributedStrM.append(dataString)
            cell.titleLabel.attributedText = attributedStrM
        }
        
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                cell.CloseButton.isHidden = true
                cell.titleLabel.textColor = kRGBColorFromHex(rgbValue: 0x888888) //推荐 特殊设置
            }else {
                if  isEdited == true {
                    cell.titleLabel.isUserInteractionEnabled = false
                    cell.CloseButton.isHidden = false
                    cell.layer.borderColor = UIColor.clear.cgColor
                }
                if  isEdited == false {
                    cell.titleLabel.isUserInteractionEnabled = true
                    cell.CloseButton.isHidden = true
                    cell.layer.borderColor = kRGBColorFromHex(rgbValue: 0xeeeeee).cgColor
                }
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        editIndexPath = indexPath
        print(indexPath.row)
        
        if indexPath.section == 0 { // 我的频道 点击设置
            if indexPath.row != 0 && isEdited == true {
                self.CloseItemClick()
                return
            }
        }
        
        if indexPath.section == 1 {  // 推荐频道 点击设置
            let alertController = UIAlertController(title: "确认添加", message: "是否确认添加该频道", preferredStyle: .alert)
            let cancelAction1 = UIAlertAction(title: "确定", style: .default, handler: { (UIAlertAction) in
                if self.DataAry.count > 1 {
                    var MYArray = self.DataAry[0] as! [String]
                    var RemArray = self.DataAry[1] as! [String]
                    let itemString = RemArray[indexPath.row]
                    MYArray.append(itemString)
                    RemArray.remove(at: (self.editIndexPath?.row)!)
                    self.DataAry[0] = MYArray
                    self.DataAry[1] = RemArray
                    self.MainCollectionView.reloadData()
                }
            })
            let cancelAction2 = UIAlertAction(title: "取消", style: .cancel, handler: { (UIAlertAction) in
                print("dd")
            })
            alertController.addAction(cancelAction1)
            alertController.addAction(cancelAction2)
            UIViewController.getCurrentController()?.present(alertController, animated: true, completion: nil)
        }
    }
    
    //这个是设定header和footer的方法，根据kind不同进行不同的判断即可
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let TextLabelAry = ["我的频道","频道推荐"]
        let DetailsLabelAry = ["长按拖拽排序","点击添加频道"]
        
        if kind == UICollectionElementKindSectionHeader {
            let HIMECollectionHeadView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HIMECollectionHeadV", for: indexPath) as! HIMECollectionHeadV
            
            HIMECollectionHeadView.titleLabel.text = TextLabelAry[indexPath.section]
            HIMECollectionHeadView.titleLabel.frame = CGRect(x: 12, y: 10, width: 80, height: 20)
            HIMECollectionHeadView.titleLabel.textAlignment = NSTextAlignment.left
            HIMECollectionHeadView.addSubview(HIMECollectionHeadView.titleLabel)
            
            HIMECollectionHeadView.detailLabel.text = DetailsLabelAry[indexPath.section]
            HIMECollectionHeadView.detailLabel.textColor = kRGBColorFromHex(rgbValue: 0x888888)
            HIMECollectionHeadView.detailLabel.frame = CGRect(x: 90, y: 13, width: 100, height: 15)
            HIMECollectionHeadView.detailLabel.textAlignment = NSTextAlignment.left
            HIMECollectionHeadView.addSubview(HIMECollectionHeadView.detailLabel)
            
            if indexPath.section == 0 {
                EditedBtn.setTitle("编辑", for: .normal)
                EditedBtn.setTitleColor(kRGBColorFromHex(rgbValue: 0x129aee), for: .normal)
                EditedBtn.layer.cornerRadius = 10
                EditedBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
                EditedBtn.layer.borderColor = kRGBColorFromHex(rgbValue: 0x129aee).cgColor
                EditedBtn.layer.borderWidth = 0.5
                EditedBtn.addTarget(self, action: #selector(EditedBtnClick), for: .touchUpInside)
                HIMECollectionHeadView.addSubview(EditedBtn)
                
                EditedBtn.snp.makeConstraints({ (make) in
                    make.right.equalTo(HIMECollectionHeadView).offset(-12)
                    make.top.equalTo(HIMECollectionHeadView).offset(10)
                    make.height.equalTo(24)
                    make.width.equalTo(55)
                })
            }
            return HIMECollectionHeadView
        }
        else{
            let HIMECollectionFootView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "HIMECollectionFootV", for: indexPath)
            return HIMECollectionFootView
        }
    }
    
    //header高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: UIScreen.main.bounds.size.width, height: 40.0)
    }
    //footer高度
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: UIScreen.main.bounds.size.width, height: 40.0)
    }
}

/// ----------------- HIMenuEditedCell

class HIMenuEditedCell: UICollectionViewCell {
    
    lazy var titleLabel = UILabel()
    lazy var CloseButton = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    func ConfigCellUI () {
        self.layer.cornerRadius = 8
        self.layer.borderWidth = 0.5
        self.layer.borderColor = kRGBColorFromHex(rgbValue: 0xeeeeee).cgColor
        
        self.backgroundColor = kRGBColorFromHex(rgbValue: 0xffffff)
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.textAlignment = NSTextAlignment.center
        titleLabel.frame =  self.bounds
        titleLabel.textColor = kRGBColorFromHex(rgbValue: 0x333333)
        self.contentView.addSubview(titleLabel)
        
        CloseButton.setImage(UIImage(named: "叉号"), for: .normal)
        self.contentView.addSubview(CloseButton)
        CloseButton.isHidden = true
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// -----------------  HIMECollectionHeadView
class HIMECollectionHeadV: UICollectionReusableView {
    
    lazy var titleLabel = UILabel(ffText: "", fontSize: 16, textColor: kRGBColorFromHex(rgbValue: 0x333333))
    lazy var detailLabel = UILabel(ffText: "", fontSize: 11, textColor: kRGBColorFromHex(rgbValue: 0x888888))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// ----------------- HIMECollectionFootView
class HIMECollectionFootV: UICollectionReusableView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = kRGBColorFromHex(rgbValue: 0xfafafa)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


